﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace Tailoring
{
    public partial class frmdontask : Form
    {
        string invoiceID;
        string orderid;
        string paidstatus;
        public string Orderid
        {
            get { return orderid; }
            set { orderid = value; }
        }
        string orderID = "";
        SqlDataAdapter da;
        DataSet ds;
        SqlConnection conn = new SqlConnection("Server= localhost; database=tailoringmng; integrated Security=true");
        public string pid { set { txtid.Text = value; } get { return txtid.Text; } }
        public string pname { set { txtname.Text = value; } get { return txtname.Text; } }
        public string pmobile { set { txtmobile.Text = value; } get { return txtmobile.Text; } }
        //public string pddatekey { set { txtcnic.Text = value; } get { return txtcnic.Text; } }
        public string porderid { set { orderID = value; } }
        public frmdontask()
        {
            InitializeComponent();
        }
        public void saveinvoice()
        {

            try
            {
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn.Open();
                
            
            string query = "Select invoiceId from tblinvoice where invoiceId="+(orderID+txtid.Text);
            SqlCommand cmdck = new SqlCommand(query,conn);            
            SqlDataReader dr = cmdck.ExecuteReader();
            if (dr.HasRows)
            {                
               
                    invoiceID = (orderID+txtid.Text)+"1";
                }
                else
                {
                    invoiceID = (orderID + txtid.Text);
                }
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into tblinvoice values(@invoiceid,@oid,@cid,@date)", conn);
                cmd.Parameters.AddWithValue("@invoiceid", invoiceID);
                cmd.Parameters.AddWithValue("@oid", orderID);
                cmd.Parameters.AddWithValue("@cid", txtid.Text);
                cmd.Parameters.AddWithValue("@date", DateTime.Now.ToString());
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter adapter = new SqlDataAdapter();
                adapter.InsertCommand = cmd;
                adapter.InsertCommand.ExecuteNonQuery();
                cmd.Connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                this.conn.Close();

            }
        }

        private void fnSaveUpdate() 
{
   try 
   { 
      //put the modified DataSet into a new DataSet(myChangedDataset) 
      DataSet myChangedDataset= this.ds.GetChanges(); 
      if (myChangedDataset != null) 
     { 
        //get how many rows changed 
        int modifiedRows = this.da.Update(myChangedDataset); 
        MessageBox.Show("Database has been updated successfully: " + 
                      modifiedRows + " Modified row(s) ", "Success"); 
        this.ds.AcceptChanges(); //accept the all changes 
        //fnRefresh(); 
     } 
     //else 
     //} 
     //   MessageBox.Show("Nothing to save", "No changes"); 
     // }//if-else 
   } 
   catch(Exception ex) 
  { 
     //if something somehow went wrong 
    MessageBox.Show("An error occurred updating the database: " + 
      ex.Message, "Error",  MessageBoxButtons.OK, MessageBoxIcon.Error); 
    this.ds.RejectChanges(); //cancel the changes 
  }//try-catch 
  //fnEnableDisableAllButtons(true);
}

        public void orderDetail(string ClientId)
        {

            try
            {
                conn.Open();
                string strquery = "select * from tblclientinfo where clientId=" + ClientId;
                SqlCommand sqlcmd = new SqlCommand("delevery", conn);
                sqlcmd.Parameters.AddWithValue("@cid", ClientId);
                sqlcmd.Parameters.AddWithValue("@oid", orderID);
                //sqlcmd.Parameters.AddWithValue("@ddate", ddate);

                sqlcmd.CommandType = CommandType.StoredProcedure;
                SqlDataReader sqldreader = sqlcmd.ExecuteReader();
                if (sqldreader.HasRows)
                {
                    //MessageBox.Show("This Customer Has");
                    while (sqldreader.Read())
                    {
                        txtid.Text = sqldreader["clientId"].ToString();
                        txtname.Text = sqldreader["name"].ToString();
                        txtmobile.Text = sqldreader["mobile"].ToString();
                        txtcnic.Text = sqldreader["city"].ToString();
                        txtnoofcloths.Text = sqldreader["nubmerOfCloths"].ToString();
                        txtstatus.Text = sqldreader["odrstatus"].ToString();
                        txtddate.Text = String.Format("{0:dd MMMM yyyy}", sqldreader["DDate"]);
                        txtorderdate.Text = String.Format("{0:dd MMMM yyyy}", sqldreader["CDate"]);
                        txtbal.Text = sqldreader["amountBal"].ToString();
                        txttotal.Text = sqldreader["totalAmount"].ToString();
                        txtrec.Text = sqldreader["amountRece"].ToString();
                    }
                }
                else
                {
                    MessageBox.Show("No Data Found !");
                }
                sqldreader.Close();
                conn.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void loaddgacount(string cid)
        {

            {
                try
                {

                    SqlConnection conn = new SqlConnection("Server= localhost; database=tailoringmng; integrated Security=true");
                    SqlCommand cmd = new SqlCommand("spiaccount", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@id", cid);
                    //cmd.Parameters.AddWithValue("@oid", oid);
                    da = new SqlDataAdapter(cmd);

                    if (conn == null && conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }

                    ds = new DataSet();
                    da.Fill(ds, "dbo.tblaccount");
                    //BindingSource bs = new BindingSource();
                    //bs.DataSource = ds;
                    
                    accountgrid.DataSource = ds.Tables[0];
                    
                    conn.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);

                }
            }
        }
        

        public void updateOrderTask(string cid, string oid, string statuskey, string ddatekey)
        {
            try
            {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            //conn.Open();
            SqlCommand cmd = new SqlCommand("updatesatus", conn);
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;


            cmd.Parameters.AddWithValue("@orderStatus", statuskey);
            cmd.Parameters.AddWithValue("@id", cid);
            cmd.Parameters.AddWithValue("@ddate", ddatekey);
            cmd.Parameters.AddWithValue("@oid", oid);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.InsertCommand = cmd;
            int a = adapter.InsertCommand.ExecuteNonQuery();
            cmd.Connection.Close();
            ////if (a == -1)
            ////{
            //    MessageBox.Show("Update Successfull...");
            ////}

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                this.conn.Close();

            }

        }
        public void updateaccount(string cid, string oid,string pstatus, string bal, string rec)
        {
            if (MessageBox.Show("Are You Sure Want to Make this Payment? Which Cannot be Revoke ?",
                            "Incoice Payment Confirmation?",
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    //conn.Open();
                    SqlCommand cmd = new SqlCommand("updatebal", conn);
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.StoredProcedure;


                    cmd.Parameters.AddWithValue("@amtrec", rec);
                    cmd.Parameters.AddWithValue("@id", cid);
                    cmd.Parameters.AddWithValue("@amtbal", bal);
                    cmd.Parameters.AddWithValue("@oid", oid);
                    cmd.Parameters.AddWithValue("@paidstatus", pstatus);
                    SqlDataAdapter adapter = new SqlDataAdapter();
                    adapter.InsertCommand = cmd;
                    int a = adapter.InsertCommand.ExecuteNonQuery();
                    cmd.Connection.Close();
                    //if (a == -1)
                    //{
                    if (MessageBox.Show("Invoice Paid Succeded! Do Want to Print the Invoice? ", "Update Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        
                        frminvoice rpt = new frminvoice();
                        rpt.Cid = Convert.ToInt32(txtid.Text);
                        rpt.Oid = Convert.ToInt32(orderID);
                        
                        rpt.Show();
                    }
                   

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);

                }


                finally
                {
                    saveinvoice();
                    this.conn.Close();

                }
            }
            this.Refresh();
        }

        private void frmdontask_Load(object sender, EventArgs e)
        {
            //if (txtname.Text == "")
            //{
            //    MessageBox.Show("No Data Found Try Agian ");
            //    this.Close();
            //}
            txtpay.Text = "0";
            loaddgacount(txtid.Text);
            
        }

        private void txtid_Click(object sender, EventArgs e)
        {
            txtid.Text = "";

        }

        private void accountgrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            fnSaveUpdate();
        }

        private void accountgrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == accountgrid.Columns["btncolPaid"].Index && e.RowIndex >= 0)
            {
                int selectedrowindex=accountgrid.SelectedCells[0].RowIndex;
                DataGridViewRow SetedRows=accountgrid.Rows[selectedrowindex];

                updateaccount(txtid.Text, Convert.ToString(SetedRows.Cells["Order ID"].Value), "Paid", "0", Convert.ToString(SetedRows.Cells["Total Amount"].Value));
           
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string idkey = txtid.Text;
            string ddate = txtddate.Text;
            string statusorder = "Undone";
            updateOrderTask(idkey, orderID, statusorder, ddate);
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("All Invoice Will be Made Paid Which Cannot be Revoke ?",
                        "Do You Readlly Want to Make All invoice Paid?",
                         MessageBoxButtons.YesNo,
                         MessageBoxIcon.Warning) == DialogResult.Yes)
            {


                try
                {
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    //conn.Open();
                    SqlCommand cmd = new SqlCommand("update tblaccount set paid='Paid' where clientId="+txtid.Text, conn);
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    SqlDataAdapter adapter = new SqlDataAdapter();
                    adapter.InsertCommand = cmd;
                    int a = adapter.InsertCommand.ExecuteNonQuery();
                    cmd.Connection.Close();
                    
                        MessageBox.Show("All Invoices Paid For User "+txtname);
                    

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);

                }
                finally
                {
                    this.conn.Close();

                }
            }
            this.Refresh();

        }

        private void btnpaid_Click(object sender, EventArgs e)
        {
            
            string idkey = txtid.Text;
            string ddate = txtddate.Text;
            
            updateOrderTask(idkey, orderID, "Completed", ddate);
            paidstatus = "Paid";
            updateaccount(txtid.Text, orderID, paidstatus,"0", txttotal.Text);
            
            this.Close();
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            this.Size = new Size(693,625);
            linkLabel2.Text = "";
        }

        private void txtpay_TextChanged(object sender, EventArgs e)
        {
            
            
        }

        private void txtpay_Leave(object sender, EventArgs e)
        {
            int bal = Convert.ToInt32(txtbal.Text);
            int pay = Convert.ToInt32(txtpay.Text);
            int rec = Convert.ToInt32(txtrec.Text);
            int newbal = (bal - pay);
            txtbal.Text = newbal.ToString();
            int newrec = rec + pay;
            txtrec.Text = newrec.ToString();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (txtbal.TextLength > 0)
            {
                paidstatus = "Half";
                
            }
            else
            {

                paidstatus = "Paid";
                //updateOrderTask(txtid.Text, orderID, "Completed", txtddate.Text);
            }
            
            updateaccount(txtid.Text, orderID, paidstatus,txtbal.Text, txtrec.Text);
            updateOrderTask(txtid.Text, orderID, "Completed", txtddate.Text);

        }

        private void txtpay_Validating(object sender, CancelEventArgs e)
        {

        }

        private void txtpay_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
                      && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
        }
    }
}
